package server

import (
	"fmt"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/db/mysql/db_main"
	"longmen/server/pkg/db/mysql/models/models_main"
	pb "longmen/server/pkg/protobuf"
	"time"
)

type Server struct {
	pb.UnimplementedHongBaoServerServer
}

/**
* @Author:admin
* @Description: 回退还未有领完的红包
* @Param :
* @Return :
* @Date: 14:08 2022/6/15
 */
// 200豪秒一个轮循

func (s *Server) BackHongBaoList() {
	for {
		list, err := db_main.GetHongBaoList(generateBackListParam(), "create_time asc")
		if err == nil {
			for _, hongBao := range list {
				commitBackHongBao(hongBao)
			}
		}
		fmt.Println("-----------定时任务已开启-----------------")
		time.Sleep(time.Duration(_const.BACK_HONG_BACK_POLLING_TIME) * time.Second)
	}
}

/**
 * @Author admin
 * @Description //消费队列
 * @version: v1.8.0
 * @Date 11:12 2022/7/11
 * @Param
 * @return
 **/
func (s *Server) ConsumerDiamondQueue() {
	commitTicker := time.NewTicker(time.Millisecond * _const.HONG_BAO_COMMIT_TICKER)
	//FIXME 测试语句
	//commitTicker := timehelper.NewTicker(timehelper.Second * 8)
	//批量提交到数据库
	//1. 两个条件，时间与 总条数 优先条件为总条数，如果在循环间隔时间之内先收集到1000，就会提交数据库
	//2.如果在时间间隔之内还未有到集到1000，但时间已到达，提交数据到数据库
	diamondList := make([]*models_main.Diamond, 0)
	for {
		select {
		case diamond := <-diamondQueue:
			//diamondList = append([]*models.Diamond{diamond}, diamondList...)
			diamondList = append(diamondList, diamond)
			conditionAction(&diamondList, _const.HONG_BAO_BATCH_SIZE)
		case <-commitTicker.C:
			conditionAction(&diamondList, 0)
		}
	}
}

/**
 * @Author admin
 * @Description // 根据条件批量入库
 * @version: v1.8.0
 * @Date 11:12 2022/7/11
 * @Param
 * @return
 **/
func conditionAction(diamondList *[]*models_main.Diamond, condition int) {
	if len(*diamondList) > condition {
		go retryBatchSaveDiamondToDb(*diamondList, _const.RETRY_TIME)
		*diamondList = make([]*models_main.Diamond, 0)
	}
}
